<template>
    <el-dialog
      :model-value="visible"
      width="720px"
      title="创建系统"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :key="formKey"
        :model="form"
        :rules="rules"
        label-width="92px"
        class="layer-form"
      >
        <el-card shadow="hover" class="layer-card">
          <template #header>
            <div class="card-head">
              <div class="title">
                <el-tag size="small" type="primary" effect="plain">系统</el-tag>
                <!-- <span class="path-preview">{{ pathPreview }}</span> -->
              </div>
            </div>
          </template>
  
          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="系统编码" prop="code">
                <el-input v-model="form.code" placeholder="系统编码（唯一，必填）" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="系统名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入名称" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="归属部门" prop="deptId">
                <el-tree-select
                  v-model="form.deptId"
                  :data="deptOptions"
                  :props="{ value: 'id', label: 'label', children: 'children' }"
                  value-key="id"
                  placeholder="请选择归属部门"
                  check-strictly
                />
              </el-form-item>
            </el-col>
  
            <el-col :span="12">
              <el-form-item label="系统状态" prop="status">
                <el-select v-model.number="form.status" placeholder="请选择系统状态">
                  <el-option
                    v-for="d in asset_node_status"
                    :key="d.value"
                    :label="d.label"
                    :value="Number(d.value)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
  
          <!-- 可按需保留/删除的扩展字段（与你原表单保持一致，便于复用后端结构） -->
          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="系统类别">
                <el-input v-model="form.beType" placeholder="" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="区域">
                <el-input v-model="form.area" placeholder="" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="规格">
                <el-input v-model="form.specification" placeholder="" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="材质">
                <el-input v-model="form.material" placeholder="" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="单位">
                <el-input v-model="form.unit" placeholder="例：套" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数量">
                <el-input v-model="form.quantity" placeholder="" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="金额(万)">
                <el-input v-model="form.amount" placeholder="" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="特种设备">
                <el-select v-model.number="form.isSpecial" placeholder="请选择">
                  <el-option label="是" :value="1" />
                  <el-option label="否" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-form-item label="备注说明">
            <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="可空" />
          </el-form-item>
        </el-card>
      </el-form>
  
      <template #footer>
        <el-button @click="close()">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submit">创建</el-button>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref, reactive, computed, onMounted, getCurrentInstance } from "vue";
  import { ElMessage } from "element-plus";
  import { createRoute } from "@/api/sbtz/sbtz";
  import { deptTreeSelect } from "@/api/system/user";
  
  const props = defineProps({
    /** 由父级用 v-model 控制可见性；也可用暴露的 open()/close() 控制 */
    modelValue: { type: Boolean, default: false },
    /** 创建成功后是否保持弹窗不关闭（默认 true，与您原逻辑一致） */
    stayOpenAfterCreate: { type: Boolean, default: true }
  });
  const emit = defineEmits(["update:modelValue", "success", "error", "close"]);
  
  const { proxy } = getCurrentInstance();
  const { asset_node_status } = proxy.useDict?.("asset_node_status") || { asset_node_status: [] };
  
  const visible = ref(false);
  const submitting = ref(false);
  const formRef = ref(null);
  const formKey = ref(0)
  const form = reactive(makeEmptySystem())
  
  const deptOptions = ref([]);
  const deptMap = new Map();
  function buildDeptTree(nodes = []) {
    return nodes.map(n => {
      const children = buildDeptTree(n.children || []);
      const node = { ...n, children, disabled: children.length > 0 };
      deptMap.set(n.id, node);
      return node;
    });
  }
  function isLeafDeptId(id) {
    const node = deptMap.get(id);
    return !!node && (!node.children || node.children.length === 0);
  }
  
  async function loadDept() {
    try {
      deptMap.clear();
      const res = await deptTreeSelect();
      deptOptions.value = buildDeptTree(res?.data || []);
    } catch {
      deptOptions.value = [];
    }
  }
  
 
  
  function makeEmptySystem() {
    return {
      nodeType: "SYSTEM",
      name: "",
      code: "",
      remark: "",
      specification: "",
      model: "",
      material: "",
      power: "",
      brand: "",
      manufacturer: "",
      isSpecial: null,
      deptId: null,
      status: 0,
      // 扩展字段（与你原提交结构兼容）
      mokuai: null,
      area: null,
      designTemp: null,
      designPress: null,
      motorPower: null,
      mixingType: null,
      beType: null,
      unit: null,
      quantity: null,
      amount: null
    };
  }
  
  const rules = {
    name: [{ required: true, message: "请输入名称", trigger: "blur" }],
    code: [{ required: true, message: "请输入编码", trigger: "blur" }],
    deptId: [{ required: true, message: "请选择部门", trigger: "blur" }]
  };
  
  const pathPreview = computed(() => {
    const n = form.name?.trim();
    return n ? n + (form.code ? `(${form.code})` : "") : "—";
  });
  
  function open() {
    visible.value = true;
    // 初始化/重置
    Object.assign(form, makeEmptySystem());
    loadDept();
  }
  function close() {
    visible.value = false;
  }
  
  function handleClose() {
    emit("close");
  }
  
  async function submit() {
    // 基础校验
    await formRef.value?.validate();
    if (form.deptId && !isLeafDeptId(form.deptId)) {
      return ElMessage.error("“归属部门”必须选择具体部门（不能选目录/公司层）");
    }
  
    const payload = {
      startParentId: 0,         // ← 创建系统固定为根
      reuseCode: false,
      layers: [
        {
          nodeType: "SYSTEM",
          name: form.name,
          code: form.code,
          spareIds: [],
          remark: form.remark,
          specification: form.specification,
          model: form.model,
          material: form.material,
          power: form.power,
          brand: form.brand,
          manufacturer: form.manufacturer,
          isSpecial: form.isSpecial,
          deptId: form.deptId,
          status: form.status,
  
          mokuai: form.mokuai ?? null,
          area: form.area ?? null,
          designTemp: form.designTemp ?? null,
          designPress: form.designPress ?? null,
          motorPower: form.motorPower ?? null,
          mixingType: form.mixingType ?? null,
          beType: form.beType ?? null,
          unit: form.unit ?? null,
          quantity: form.quantity ?? null,
          amount: form.amount ?? null
        }
      ]
    };
  
    submitting.value = true;
    try {
      const res = await createRoute(payload);
      if (res?.code === 200) {
        ElMessage.success("系统创建成功");
        emit("success", res);
        if (props.stayOpenAfterCreate) {
          // 保持开启：仅清空表单，便于连续创建
          Object.assign(form, makeEmptySystem());
          await loadDept(); // 若部门有新增，也能刷新
        } else {
          close();
        }
      } else {
        ElMessage.error(res?.msg || "创建失败");
        emit("error", res);
      }
    } catch (e) {
      ElMessage.error(e?.msg || "创建失败");
      emit("error", e);
    } finally {
      submitting.value = false;
    }
  }
  
  // v-model 兼容（外部也可直接用 ref 调用 open/close）
  watch(
    () => props.modelValue,
    v => {
      visible.value = v;
      if (v) {
        Object.assign(form, makeEmptySystem());
        loadDept();
      }
    },
    { immediate: true }
  );
  watch(visible, v => emit("update:modelValue", v));

  function resetFormState() {
    // 重新挂载表单，清除一切校验 DOM 状态
    formKey.value += 1
    // 重置数据（新的初始态）
    Object.assign(form, makeEmptySystem())
  }

  watch(() => props.modelValue, async (v) => {
    visible.value = v
    if (v) {
      resetFormState()
      await nextTick()
      // 保险：有时 key 未生效或异步校验残留
      formRef.value?.clearValidate?.()
    }
  })
  
  onMounted(() => {
    if (visible.value) loadDept();
  });
  
  // 暴露方法给父组件
  defineExpose({ open, close, submit });
  </script>
  
  <style scoped>
  .layer-card { border-radius: 12px; }
  .card-head { display: flex; align-items: center; justify-content: space-between; }
  .card-head .title { display: flex; align-items: center; gap: 8px; font-weight: 500; }
  .path-preview { color: #909399; }
  .layer-form :deep(.el-input),
  .layer-form :deep(.el-select),
  .layer-form :deep(.el-input-number) { width: 100%; }
  </style>
  